export function useMaxCellWidth (data = []) {
  let cells = new Map()

  data.slice(0, Math.min(data.length, 50)).forEach(item => {
    Object.keys(item).forEach(key => {
      const len = String(item[key] || '').length

      const note = cells.has(key) ? cells.get(key).length : 0

      if (len > note) {
        cells.set(key, String(item[key] || ''))
      }
    })
  })

  return cells
}

export function useColumnWidth (columns = []) {
  let cells = new Set()

  columns.forEach(item => {
    const text = String(item['headerText'] || '')

    cells.set(item['field'], text)
  })

  return cells

}


export function useTableColumn (data = [], columns = [], options = {}) {
  let columnWidth = 0
  let needWith = 0

  let len = 0

  const maxContent = useMaxCellWidth(data)

  const { tableWidth, fontSize, fontWeight } = options


  columns.forEach((item, index) => {
    if (item.visible) {
      const headerText = String(item['headerText'] || '')
      const contentText = maxContent.has(item.field) ? maxContent.get(item.field) : ''

      const headerTextWidth = getTextWidth(headerText) + 30
      const contentTextWidth = getTextWidth(contentText, `${fontWeight} ${fontSize}px Microsoft YaHei`)
    
      item._textWidth = contentTextWidth

      if (contentTextWidth <= headerTextWidth) {
        item.width = headerTextWidth

      } else if (contentTextWidth <= headerTextWidth * 3) {
        item.width = contentTextWidth
        item._needWidth = 0
      } else if (contentTextWidth > headerTextWidth * 3 && contentTextWidth <= headerTextWidth * 10) {
        item.width = 250
        needWith += contentTextWidth - item.width
        item._needWidth = contentTextWidth - item.width
      } else {
        item.width = 400
        needWith += contentTextWidth - item.width
        item._needWidth = contentTextWidth - item.width
      }


      columnWidth += item.width
      len += 1

      
    }
  })

  if (tableWidth > columnWidth) {
    const allocableWidth = tableWidth - columnWidth - 5
    if (needWith < allocableWidth) {
      const averageWidth = (allocableWidth - needWith) / len
      columns.forEach((item, index) => {
        item.width = item.width >= 250 ? item._textWidth + averageWidth : item.width + averageWidth
      })
    } else {
      columns.forEach((item, index) => {
       
        if (item.width >= 250) {
          item.width = item.width + (item._needWidth / needWith) * allocableWidth
        }

      })
    }
  }
}

export function getTextWidth (text, font = "700 14px Microsoft YaHei") {
  const canvas = document.createElement("canvas");
  let context = canvas.getContext("2d");
  context.font = font
  let textmetrics = context.measureText(text)
  return Math.ceil(textmetrics.width);
}
